package com.qf.filter;

import com.qf.tenant.entity.Tenant;
import com.qf.utils.JWTUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 作者：WXH
 * 时间：2023/10/28
 * 描述：冲冲冲！！！
 */
public class TokenFilter extends BasicAuthenticationFilter {
    public TokenFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        //获取请求头中的token
        String token = request.getHeader("token");
        //解析token
        try {
            Tenant tenant = JWTUtil.verifyToken(token);
            //获取权限
            Collection<SimpleGrantedAuthority> authorities = new ArrayList<>();
            List<String> perms = tenant.getPerms();
            if (perms!=null&&perms.size()!=0){
                for (String perm : perms) {
                    authorities.add(new SimpleGrantedAuthority(perm));
                }
            }


            //将user信息放入securityContext中
            UsernamePasswordAuthenticationToken upa = new UsernamePasswordAuthenticationToken(tenant,null,authorities);

            SecurityContextHolder.getContext().setAuthentication(upa);
        } catch (Exception e) {
            //e.printStackTrace();
        }

        //放行
        chain.doFilter(request,response);

        //清除securityContext中的信息
        SecurityContextHolder.clearContext();
    }
}
